const api = require('../../config/wechatcommite.js');
const apiDic = require('../../config/api.js');
import Toast from '@vant/weapp/toast/toast';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    showProp: false,
    showFile: false,
    showWeChat: true,
    fileList: [],
    title: '房企',
    barData: {},
    list: [],
    templateList: [],
    costList: [],
    value: '',
    src: ''
  },
  toPay(url, name) {
    let this_ = this;
    let openid = wx.getStorageSync('openid')
    let downloadAmount = this.data.downloadAmount
    if (downloadAmount != 0) {
      wx.request({
        url: apiDic.wxPay,
        method: 'GET',
        data: {
          openid: openid,
          amount: downloadAmount,
          description: "download file to disk",
          vipGradeId: -1
        },
        success: (res) => {
          wx.hideLoading();
          if (res.data.code == 200) {
            this_.setData({
              param: res.data.data
            })
            this_.pay(JSON.parse(res.data.data), url, name)
          } else {
            wx.showToast({
              title: "网络异常！"
            })
          }
        },
        fail: (res) => {
          wx.hideLoading();
        }
      })
    } else {
      this_.downloadFile(url, name)
    }

  },
  //支付
  pay: function (param, url, name) {
    var that = this;
    wx.requestPayment({
      timeStamp: param.timeStamp,
      nonceStr: param.nonceStr,
      package: param.package,
      signType: param.signType,
      paySign: param.paySign,
      success: function (res) {
        that.downloadFile(url, name)
      },
      fail: function (res) {},
      complete: function (res) {}
    })
  },
  saveToDisk(e) {
    let platform = this.data.platform
    if (platform == 'ios' || platform == 'android') {
      wx.showToast({
        title: '请登录电脑版！下载文件',
        icon: 'error',
        duration: 3000
      })
      return
    }
    const url = e.currentTarget.dataset.url
    const name = e.currentTarget.dataset.name

    // wx.getSavedFileList({
    //   success(res){
    //     console.log("success已下载的文件：",res)
    //   },
    //   complete(res){
    //     console.log("complete已下载的文件：",res)
    //   }
    // })
    //先支付
    this.toPay(url, name)
  },
  downloadFile(url, name) {
    wx.showLoading({
      title: '下载中...',
    })
    var first = url.lastIndexOf(".");//取到文件名开始到最后一个点的长度
    var namelength = url.length;//取到文件名长度
    var filesuffix = url.substring(first + 1, namelength );//截取获得后缀名
    console.log("文件后缀：",filesuffix)
    const writeFilePath = `${wx.env.USER_DATA_PATH}/${name}` + '.'+filesuffix
    wx.downloadFile({
      url: url,
      filePath:writeFilePath,
      timeout:1000*60*10,
      success(res) {
        if (res.statusCode === 200) {
          
          const filePath = res.tempFilePath
          console.log(filePath)
          // const savedFilePath = wx.getFileSystemManager().saveFileSync(filePath, writeFilePath)
          wx.saveFileToDisk({
            filePath: writeFilePath,
            success(res) {
              console.log("saveFileToDisk success: ",res)
            },
            fail(res) {
              console.log("saveFileToDisk fail: ",res)
            },
            complete(re) {
              wx.hideLoading()
              // wx.getFileSystemManager().unlink({
              //   filePath: savedFilePath,
              //   success(res) {},
              //   complete(e) {}
              // })
              if (re.errMsg != null && re.errMsg.indexOf("fail") > -1) {
                wx.showToast({
                  title: '下载错误，请登录电脑版！',
                  icon: 'error',
                  duration: 3000
                })
              }
            }
          })
        }
      }
    })
  },

  lookBigPic(e) {
    const {
      value
    } = e.currentTarget.dataset
    const {
      src
    } = e.currentTarget.dataset
    wx.previewImage({
      urls: [src],
    })
  },
  onFileClose() {
    this.setData({
      showFile: false
    })
  },
  clickTemplate(e) {
    let status = this.valided()
    if (status) {
      let remark = e.currentTarget.dataset.remark;
      let list = JSON.parse(remark || '[]')
      //绑定模板数据
      if (list && list.length) {
        this.setData({
          showFile: true,
          fileList: list
        })
      }
    }

  },
  clickFile(e) {
    let url = e.currentTarget.dataset.url;
    if (url) {
      this.openTemplateFile(url)
    }
  },
  openTemplateFile(fileUrl) {
    if (!fileUrl) {
      return
    }
    let platform = this.data.platform
    if (platform != 'ios' && platform != 'android') {
      // wx.showToast({
      //   title: '请登录电脑版！下载文件',
      //   icon: 'error',
      //   duration: 3000
      // })
      // return
      if(fileUrl.indexOf("pdf") == -1 && fileUrl.indexOf("doc") == -1){
      wx.showToast({
        title: '请点击下载文件',
        icon: 'error',
        duration: 3000
      })
      return
      }
    }
    let that = this
    //判断文件是否大于标准值 大于就不让预览
    this.onFileClose()
    wx.showLoading({
      title: "正在打开文件..."
    })
    var first = fileUrl.lastIndexOf(".");//取到文件名开始到最后一个点的长度
    var namelength = fileUrl.length;//取到文件名长度
    var filesuffix = fileUrl.substring(first + 1, namelength );//截取获得后缀名
    console.log("文件链接：",fileUrl)
    wx.downloadFile({
      url: fileUrl,
      success: function (res) {
        console.log(res)
        var filePath = res.tempFilePath
        // debugger
        console.log("文件原始大小：", res)
        let dataSize = JSON.parse(JSON.stringify(res.header).replace("Content-Length","ContentLength"))
        console.log(dataSize)
        console.log(dataSize.ContentLength)
        console.log("文件大小：", dataSize.ContentLength / 1024 / 1024)
        if (dataSize.ContentLength / 1024 / 1024 > that.data.standardValue) {
          // Toast.fail('文件较大,请登录电脑微信下载预览!');
          Toast('文件较大,请登录电脑微信下载预览!');
          wx.hideLoading()
          return;
        }
        // let name = 123
        // const writeFilePath = `${wx.env.USER_DATA_PATH}/${name}` + '.'+filesuffix
        // const savedFilePath = wx.getFileSystemManager().saveFileSync(filePath, writeFilePath)
        console.log("filesuffix",filesuffix)
        wx.openDocument({
          filePath: filePath,
          fileType: filesuffix,
          success: function (res) {
            console.log('打开文档成功', res)
            wx.hideLoading()
          }
        })
      }
    })
  },
  onChangeTab(e) {
    let {
      index
    } = e.detail
    if (index === 0) {
      this.setData({
        showWeChat: true
      })
    } else {
      this.setData({
        showWeChat: false
      })
    }

  },


  getDictDataList() {
    wx.request({
      url: apiDic.dictDataListUrl,
      data: {
        type: 'resource_template'
      },
      method: 'GET',
      success: (res) => {
        if (res.data.code === 200) {
          let data = res.data.data
          this.setData({
            templateList: data
          })
        }
      }
    });
  },

  getCostDataList() {
    wx.request({
      url: apiDic.dictDataListUrl,
      data: {
        type: 'cost_template'
      },
      method: 'GET',
      success: (res) => {
        if (res.data.code === 200) {
          let data = res.data.data
          this.setData({
            costList: data
          })
        }
      }
    });
  },



  getName() {
    this.setData({
      barData: [{
          id: 1,
          dictLabel: '建筑工程实用表格',
          dictValue: '0',
        },
        {
          id: 2,
          dictLabel: '全国造价信息',
          dictValue: '1',
        }
      ]
    })
  },
  valided() {
    this.setData({
      showProp: false
    })
    let hasUser = getApp().hasUser()
    console.log("hasUser status", hasUser)
    if (!hasUser) {
      this.setData({
        showProp: true,
        onConfirmId: 0
      })
      console.log("hasUser", this.data.onConfirmId)
      return false
    } else {
      let hasPhone = getApp().hasPhone()
      console.log("hasPhone status", hasPhone)
      if (!hasPhone) {
        let user = wx.getStorageSync('wxUser')
        let wxName = user.wxName
        let wxUrl = user.wxUrl
        console.log("hasPhone user ", user)
        this.setData({
          showProp: true,
          onConfirmId: 1,
          userInfo: {
            avatarUrl: wxUrl,
            nickName: wxName
          }
        })
        return false
      }
      console.log("hasPhone", this.data.onConfirmId)
    }
    return true
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getName()
    this.getDictDataList()
    this.getCostDataList()
    //获取设备信息
    this.getSystemInfo()
    //获取系统自定义参数 下载金额
    this.getDownloadAmount()
    //获取系统自定义参数 预览文件标准值
    this.getStandardValue()
  },
  getDownloadAmount() {
    wx.request({
      url: apiDic.sysConfig,
      data: {
        configKey: 'downloadAmount'
      },
      method: 'GET',
      success: (res) => {
        if (res.data.code === 200) {
          let data = parseInt(res.data.sysConfig.configValue)
          this.setData({
            downloadAmount: data
          })
        }
      }
    });

  },
  getStandardValue() {
    wx.request({
      url: apiDic.sysConfig,
      data: {
        configKey: 'standardValue'
      },
      method: 'GET',
      success: (res) => {
        if (res.data.code === 200) {
          let data = parseInt(res.data.sysConfig.configValue)
          this.setData({
            standardValue: data
          })
        }
      }
    });

  },
  getSystemInfo() {
    let that = this
    wx.getSystemInfo({
      success(res) {
        that.setData({
          platform: res.platform
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.valided()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {}
})